<?php

namespace App\Services\ApplyProductOrderRefund;

use Carbon\Carbon;
use App\Models\OrderItem;
use Illuminate\Validation\Rule;
use App\Http\Controllers\Api\V1\Requests\FormRequest;

class ApplyProductOrderRefundRequest extends FormRequest
{
	/**
	 * @var OrderItem
	 */
	protected $item;
	
	public function rules()
	{
		return [
			'item_id' => ['required', 'integer', $this->item()],
			'type' => Rule::in(array_keys(config("site.order.refund.types"))),
			'reason' => 'required|string',
			'parcel_status' => 'nullable|string',
			'refund_money' => ['required', 'numeric', $this->refundMoney()],
			'nego_content' => 'nullable|string|max:200',
			'proof_images' => 'nullable|array',
		];
	}
	
	public function item()
	{
		return function ($attribute, $value, $fail) {
			if (!$item = OrderItem::where('order_id',$value)->first()) {

				return $fail('目标订单不存在');
			} elseif (!$item->order->isPaid()) {
				return $fail('目标订单未支付');
			} elseif ($item->order->cancelled_at) {
				return $fail('目标订单已取消');
			} elseif (!$item->order->isProductReturnable()) {
				return $fail('目标订单商品不可申请');
			} elseif ($item->order->isGoldBeanOrder()) {
				return $fail('目标订单商品不可申请');
			} elseif ($item->order->isGoldStormOrder()) {
				return $fail('目标订单商品不可申请');
			} elseif ($item->order->created_at->addDays(15)->lt(Carbon::now())) {
				return $fail('目标订单已超出售后时间');
			}
			
			$this->item = $item;
			
			return true;
		};
	}
	
	protected function refundMoney()
	{
		return function ($attribute, $value, $fail) {
			if ($value <= 0) {
				return $fail('请输入正确的退款金额');
			} elseif ($value > $this->item->total_amount + config('site.order.refund.return_freight')) {
				return $fail('退款金额不能大于订单总额');
			} elseif ($this->item->refund) {
				return $fail('同一订单不可重复申请售后');
			}
			return true;
		};
	}
	
	public function getItem()
	{
		return $this->item;
	}
}
